package org.example.lotterysystem.controller.handler;

import org.example.lotterysystem.common.errorcode.GlobalErrorCodeConstants;
import org.example.lotterysystem.common.exception.ControllerException;
import org.example.lotterysystem.common.exception.ServiceExcetion;
import org.example.lotterysystem.common.pojo.CommonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice   //可以捕获全局抛的异常
public class GlobalExceptionHandler {
    private final static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = ServiceExcetion.class)
    public CommonResult<?> serviceException(ServiceExcetion e){
        //打印错误日志
        logger.error("ServiceExcetion：{}",e);
        //构造错误请求
        return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = ControllerException.class)
    public CommonResult<?> controllerException(ControllerException e){
        //打印错误日志
        logger.error("ControllerException：{}",e);
        //构造错误请求
        return CommonResult.error(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public CommonResult<?> Exception(Exception e){
        //打印错误日志
        logger.error("UnknownError：{}",e);
        //构造错误请求
        return CommonResult.error(GlobalErrorCodeConstants.UNKNOW_ERROR.getCode(), e.getMessage());
    }
}
